package com.oocl.o2o.admin.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.oocl.o2o.admin.dao.FailReasonDao;

import com.oocl.o2o.admin.entity.FailReason;

@Repository(value="failReasonDaoImpl")
public class FailReasonDaoImpl implements FailReasonDao{

	@PersistenceContext(name="un")
	private EntityManager manager;
	
	@Override
	public FailReason findByMerchantId(String merchantId) {
		// TODO Auto-generated method stub
		String jpql="select failReason from FailReason failReason where failReason.merchant.id=:merchantId";
		List<FailReason>failReasonList=manager.createQuery(jpql)
				.setParameter("merchantId", merchantId)
				.getResultList();
		if (failReasonList.isEmpty()) {
			return null;
		}
		else {
			return failReasonList.get(0);
		}
		
	}

	@Override
	public FailReason findByMerchantUname(String uname) {
		// TODO Auto-generated method stub
		String jpql="select failReason from FailReason failReason where failReason.merchant.uname=:uname";
		List<FailReason>failReasonList=manager.createQuery(jpql)
				.setParameter("uname", uname)
				.getResultList();
		if (failReasonList.isEmpty()) {
			return null;
		}
		else {
			return failReasonList.get(0);
		}
	}

	@Override
	public FailReason add(FailReason failReason) {
		// TODO Auto-generated method stub
		manager.persist(failReason);
		return failReason;
	}

	@Override
	public List<FailReason> findAll() {
		// TODO Auto-generated method stub
		String jpql="select failReason from FailReason failReason";
		List<FailReason>failReasonList=manager.createQuery(jpql).getResultList();
		if (failReasonList.isEmpty()) {
			return null;
		}
		else return failReasonList;
	}

	@Override
	public FailReason update(FailReason failReason) {
		// TODO Auto-generated method stub
		FailReason fReason=manager.find(FailReason.class, failReason.getId());
		//先将本来的变成游离态
		manager.clear();
		//进行游离态-->managed状态
		manager.merge(failReason);
		return failReason;
	}

	@Override
	public FailReason deleteByMerchantId(String merchantId) {
		// TODO Auto-generated method stub
		String jpql="select failReason from FailReason failReason where failReason.merchant.id=:merchantId";
		List<FailReason>failReasonList=manager.createQuery(jpql).
				setParameter("merchantId", merchantId)
				.getResultList();
		if (failReasonList.isEmpty()) {
			return null;
		}
		else{
			FailReason failReason=failReasonList.get(0);
			manager.remove(failReason);
			return failReason;
		}
		
	}

	@Override
	public FailReason delete(String id) {
		// TODO Auto-generated method stub
		FailReason failReason=manager.find(FailReason.class, id);
		manager.remove(failReason);
		return failReason;
	}

	
	
}
